package com.itheima.service.Impl;

import com.itheima.domain.Account;
import com.itheima.mapper.AccountMapper;
import com.itheima.service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {


    public void save(Account account) {

        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("sqlMapConfig");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            AccountMapper accountMapper = session.getMapper(AccountMapper.class);
            accountMapper.save(account);
            session.commit();
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public List<Account> findAll() {

        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("sqlMapConfig");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session = sqlSessionFactory.openSession();
            AccountMapper accountMapper = session.getMapper(AccountMapper.class);
            List<Account> accountList = accountMapper.findAll();
            session.close();
            return accountList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
